﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormScheduler
{
    public partial class MyForm : Form
    {
        private readonly TaskScheduler m_sysncContextTaskScheduler;
        public MyForm()
        {
            InitializeComponent();

            m_sysncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            this.textBox1.Text = "Synchroization Context Task Scheduler Demo";
            Visible = true; Width = 400; Height = 100;
        }
        private CancellationTokenSource m_cts;
        protected override void OnMouseClick(MouseEventArgs e)
        {
            if(m_cts != null)
            {
                m_cts.Cancel();
                m_cts = null;
            }
            else
            {
                this.textBox1.Text = "Operation Running";
                m_cts = new CancellationTokenSource();
                Task <Int32> t = Task.Run(()=>studies.Program.Sum(m_cts.Token,20000),m_cts.Token);
                
                t.ContinueWith(task => this.textBox1.Text = "Result : " + task.Result,
                    CancellationToken.None, 
                    TaskContinuationOptions.OnlyOnRanToCompletion, 
                    m_sysncContextTaskScheduler);

                t.ContinueWith(task=> this.textBox1.Text = "Operation Canceled",
                    CancellationToken.None,
                    TaskContinuationOptions.OnlyOnCanceled,
                    m_sysncContextTaskScheduler);

                t.ContinueWith(task=> this.textBox1.Text = "Operation Faulted",
                    CancellationToken.None,
                    TaskContinuationOptions.OnlyOnFaulted,
                    m_sysncContextTaskScheduler);
            }

            base.OnMouseClick(e);
        }
    }
}
